package com.sky.service.impl;

import com.alibaba.druid.sql.visitor.functions.Nil;
import com.sky.entity.User;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Date;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        List<Map<String, Object>> mapList = orderMapper.turnoverStatistics(begin, end);

        Map<LocalDate, Object> realMap = new LinkedHashMap<>();
        realMap.put(begin, 0);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            realMap.put(begin, 0);
        }

        for (Map<String, Object> map : mapList) {
            java.sql.Date sqlDate = (java.sql.Date) map.get("date");
            LocalDate localDate = sqlDate.toLocalDate();
            realMap.put(localDate, map.get("turnover"));
        }

        String dateList = realMap.keySet()
                .stream()
                .map(LocalDate::toString)
                .collect(Collectors.joining(", "));
        String turnoverList = realMap.values()
                .stream()
                .map(Object::toString)
                .collect(Collectors.joining(", "));

        return new TurnoverReportVO(dateList, turnoverList);
    }

    /**
     * 用户数量统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //获取前一天的数据,用以获取开始那一天的总人数
        LocalDate beforeDate = begin.plusDays(-1);
        Integer beforeUserCount = userMapper.findByBeforeDate(beforeDate);

        //进行数据初始化,主要为了对数据库中不存在的数据进行初始化,因为前端需要每天的数据
        //key: 日期, value: 本日新增人数
        Map<LocalDate, Integer> realMap = new LinkedHashMap<>();

        LocalDate currentDate = begin;
        while (!currentDate.isAfter(end)) {
            realMap.put(currentDate, 0);
            currentDate = currentDate.plusDays(1);
        }

        List<Map<String, Object>> mapList = userMapper.findByLocalDate(begin, end);
        if (mapList == null || mapList.size() == 0) {
            return new UserReportVO(StringUtils.join(realMap.keySet(), ","),
                    StringUtils.join(realMap.values(), ","),
                    StringUtils.join(realMap.values(), ","));
        }

        for (Map<String, Object> map : mapList) {
            //分别获取数据库查询出的日期及新增人数并进行数据类型转换
            //map.get("date") 获取日期
            //map.get("updateCount") 获取本日新增人数
            LocalDate date = ((Date) map.get("date")).toLocalDate();
            Integer updateCount = ((Number) map.get("updateCount")).intValue();

            //用数据库中查询出来的数据替换掉原始数据
            realMap.put(date, updateCount);
        }

        //获取每天新增人数,  本日新增人数＋昨天总人数 = 本日总人数
        ArrayList<Integer> addList = new ArrayList<>(realMap.values());
        List<Integer> totalList = new ArrayList<>();
        for (int i = 0; i < addList.size(); i++) {
            if (i == 0) {
                //对第一天进行特殊处理
                totalList.add(beforeUserCount + addList.get(i));
                continue;
            }
            //对其他数据进行正常处理
            totalList.add(totalList.get(i - 1) + addList.get(i));
        }

        //将三个集合转换为字符串
        String dateList = realMap.keySet()
                .stream()
                .map(key -> key.toString())
                .collect(Collectors.joining(","));
        String newUserList = realMap.values()
                .stream()
                .map(v -> v.toString())
                .collect(Collectors.joining(","));
        String totalUserList = totalList.stream()
                .map(t -> t.toString())
                .collect(Collectors.joining(","));
//        System.out.println(dateList);
//        System.out.println(newUserList);
//        System.out.println(totalUserList);


        //今天人数 = 昨天人数 + 新增人数

//        List<LocalDate> dateList = new ArrayList<>();
//        dateList.add(begin);
//
//        while (!begin.equals(end)){
//            begin = begin.plusDays(1);
//            dateList.add(begin);
//        }
//
//        //存放每天新增用户数
//        List<Integer> newUserList = new ArrayList<>();
//        //存放每天的总用户数据库
//        List<Integer> totalUserList = new ArrayList<>();
//
//        for (LocalDate date : dateList) {
//            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
//            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
//
//            Map map = new HashMap();
//            map.put("end",endTime);
//
//            Integer totalUser = userMapper.countByMap(map);
//            map.put("begin",beginTime);
//            Integer newUser = userMapper.countByMap(map);
//
//            totalUserList.add(totalUser);
//            newUserList.add(newUser);
//
//        }
//
//        return UserReportVO.builder()
//                .dateList(StringUtils.join(dateList,","))
//                .totalUserList(StringUtils.join(totalUserList,","))
//                .newUserList(StringUtils.join(newUserList,","))
//                .build();
        return new UserReportVO(dateList, totalUserList, newUserList);
    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //从数据库中一次性将需要的三个数据一次取出 1.日期 2.日期对应的本日所有订单 3.日期对应的本日完成订单
        List<Map<String, Object>> mapList = orderMapper.ordersStatistics(begin, end);

        //初始化数据 将位于begin和end之间的日期 及其全部订单数,已完成订单数进行初始化,方便前端调取和展示
        Map<LocalDate, Integer> totalMap = new LinkedHashMap<>();
        Map<LocalDate, Integer> completedMap = new LinkedHashMap<>();

        LocalDate currentDate = begin;
        // 使用 !isAfter 确保包含 end 日期
        while (!currentDate.isAfter(end)) {
            totalMap.put(currentDate, 0);
            completedMap.put(currentDate, 0);
            currentDate = currentDate.plusDays(1);
        }
        if (mapList == null || mapList.size() == 0){
            return new OrderReportVO(StringUtils.join(totalMap.keySet(), ","),
                    StringUtils.join(totalMap.values(), ","),
                    StringUtils.join(completedMap.values(), ","),
                    0,
                    0,
                    0.0);
        }

        //从map中提取出这三项数据,并进行数据类型转换,此时还未转换成string
        //也可以不提取,直接在for循环中使用链式编程进行数据填充
        List<LocalDate> dbDates = mapList.stream()
                .map(map -> ((Date) (map.get("date"))).toLocalDate())
                .collect(Collectors.toList());

        List<Integer> dbTotalOrder = mapList.stream()
                .map(map -> ((Number) (map.get("totalOrderCount"))).intValue())
                .collect(Collectors.toList());
        //获取订单总数
        Integer totalOrders = 0;
        for (Integer num : dbTotalOrder) {
            totalOrders += num;
        }


        List<Integer> dbCompletedOrder = mapList.stream()
                .map(map -> ((Number) (map.get("completedOrderCount"))).intValue())
                .collect(Collectors.toList());
        //获取完成订单数
        Integer completedOrders = 0;
        for (Integer num : dbCompletedOrder) {
            completedOrders += num;
        }


        Double orderCompletionRate = 0.0;
        //计算订单完成率
        if (totalOrders != 0){
            orderCompletionRate = completedOrders.doubleValue() / totalOrders.doubleValue();
        }


        //填充数据库中实际存在的数据(替换掉日期相同的key的value,数据顺序并不会发生变化)
        for (int i = 0; i < dbDates.size(); i++) {
            LocalDate date = dbDates.get(i);
            Integer totalOrder = dbTotalOrder.get(i);
            totalMap.put(date, totalOrder);
            Integer completedOrder = dbCompletedOrder.get(i);
            completedMap.put(date, completedOrder);
        }
//        System.out.println(totalMap);
//        System.out.println(completedMap);

        //从map中提取出需要的数据并转换成字符串
        String date = totalMap.keySet().stream()
                .map(key -> key.toString())
                .collect(Collectors.joining(","));
        String total = totalMap.values().stream()
                .map(v -> v.toString())
                .collect(Collectors.joining(","));
        String completed = completedMap.values().stream()
                .map(v -> v.toString())
                .collect(Collectors.joining(","));


        return new OrderReportVO(date,total,completed,totalOrders,completedOrders,orderCompletionRate);
    }

    /**
     * 销量排名
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO saleTop10(LocalDate begin, LocalDate end) {
        List<Map<String,Object>> mapList = orderDetailMapper.countByBeginAndEnd(begin,end);
        List<String> nameList = mapList.stream()
                .map(map -> (map.get("name")).toString())
                .collect(Collectors.toList());
        List<Object> numberList = mapList.stream()
                .map(map -> (map.get("saleNumber")))
                .collect(Collectors.toList());

        String name = nameList.stream().collect(Collectors.joining(","));
        String number = numberList.stream().map(num -> num.toString()).collect(Collectors.joining(","));
        System.out.println(name);
        System.out.println(number);


        return new SalesTop10ReportVO(name,number);
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        //1. 查询数据库，获取营业数据---查询最近30天的运营数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        //2. 通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //获取表格文件的Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);

            //获得第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获得第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //获得某一行
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //3. 通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
